<template>
  <div class="menus-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">系统管理——菜单管理</h1>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-section">
      <div class="action-left">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
        <el-button @click="handleExpandAll">
          <el-icon><ArrowDown /></el-icon>
          展开全部
        </el-button>
        <el-button @click="handleCollapseAll">
          <el-icon><ArrowRight /></el-icon>
          收起全部
        </el-button>
        <el-button @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="tableData"
        v-loading="loading"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        stripe
        border
        style="width: 100%"
        :default-expand-all="defaultExpandAll"
      >
        <el-table-column prop="name" label="菜单名称" width="200" />
        <el-table-column prop="path" label="路由路径" width="200" />
        <el-table-column prop="component" label="组件路径" width="200" />
        <el-table-column prop="icon" label="图标" width="100">
          <template #default="{ row }">
            <el-icon v-if="row.icon">
              <component :is="row.icon" />
            </el-icon>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status ? 'success' : 'danger'">
              {{ row.status ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="150" />
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="success" size="small" @click="handleAddChild(row)">
              新增子菜单
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="父级菜单" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="menuTreeData"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            placeholder="请选择父级菜单"
            clearable
            check-strictly
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入菜单名称" />
        </el-form-item>
        
        <el-form-item label="路由路径" prop="path">
          <el-input v-model="form.path" placeholder="请输入路由路径" />
        </el-form-item>
        
        <el-form-item label="组件路径" prop="component">
          <el-input v-model="form.component" placeholder="请输入组件路径" />
        </el-form-item>
        
        <el-form-item label="图标" prop="icon">
          <el-input v-model="form.icon" placeholder="请输入图标名称" />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-switch
                v-model="form.status"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="菜单描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入菜单描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, ArrowDown, ArrowRight, Refresh } from '@element-plus/icons-vue'
import api from '@/services/api'

export default {
  name: 'Menus',
  components: {
    Plus, ArrowDown, ArrowRight, Refresh
  },
  setup() {
    const loading = ref(false)
    const submitLoading = ref(false)
    const dialogVisible = ref(false)
    const dialogTitle = ref('新增菜单')
    const formRef = ref()
    const defaultExpandAll = ref(true)
    
    // 表格数据
    const tableData = ref([
      {
        id: 1,
        name: '系统管理',
        path: '/system',
        component: 'Layout',
        icon: 'Setting',
        sort: 1,
        status: true,
        createdAt: '2024-01-01',
        children: [
          {
            id: 2,
            name: '用户管理',
            path: '/users',
            component: 'Users',
            icon: 'User',
            sort: 1,
            status: true,
            createdAt: '2024-01-01'
          },
          {
            id: 3,
            name: '角色管理',
            path: '/roles',
            component: 'Roles',
            icon: 'UserFilled',
            sort: 2,
            status: true,
            createdAt: '2024-01-01'
          },
          {
            id: 4,
            name: '菜单管理',
            path: '/menus',
            component: 'Menus',
            icon: 'Menu',
            sort: 3,
            status: true,
            createdAt: '2024-01-01'
          }
        ]
      },
      {
        id: 5,
        name: '商品管理',
        path: '/products',
        component: 'Products',
        icon: 'Goods',
        sort: 2,
        status: true,
        createdAt: '2024-01-01',
        children: [
          {
            id: 6,
            name: '商品列表',
            path: '/products/list',
            component: 'ProductList',
            icon: 'List',
            sort: 1,
            status: true,
            createdAt: '2024-01-01'
          },
          {
            id: 7,
            name: '商品分类',
            path: '/products/category',
            component: 'ProductCategory',
            icon: 'Grid',
            sort: 2,
            status: true,
            createdAt: '2024-01-01'
          }
        ]
      }
    ])
    
    // 菜单树数据（用于选择父级菜单）
    const menuTreeData = ref([])
    
    // 表单数据
    const form = reactive({
      id: null,
      parentId: null,
      name: '',
      path: '',
      component: '',
      icon: '',
      sort: 0,
      status: true,
      description: ''
    })
    
    // 表单验证规则
    const rules = reactive({
      name: [
        { required: true, message: '请输入菜单名称', trigger: 'blur' }
      ],
      path: [
        { required: true, message: '请输入路由路径', trigger: 'blur' }
      ],
      component: [
        { required: true, message: '请输入组件路径', trigger: 'blur' }
      ]
    })
    
    // 获取菜单列表
    const fetchMenus = async () => {
      loading.value = true
      try {
        const response = await api.get('/menus')
        
        if (response.data.code === 200) {
          tableData.value = response.data.data || []
          buildMenuTree()
        }
      } catch (error) {
        const errorMessage = error.response?.data?.message || '获取菜单列表失败'
        ElMessage.error(errorMessage)
        console.error('获取菜单列表失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 构建菜单树数据
    const buildMenuTree = () => {
      const buildTree = (items, parentId = null) => {
        return items
          .filter(item => item.parentId === parentId)
          .map(item => ({
            id: item.id,
            name: item.name,
            children: buildTree(items, item.id)
          }))
      }
      
      // 扁平化所有菜单项
      const flattenMenus = (menus) => {
        let result = []
        menus.forEach(menu => {
          result.push({
            id: menu.id,
            name: menu.name,
            parentId: null
          })
          if (menu.children) {
            result = result.concat(flattenMenus(menu.children))
          }
        })
        return result
      }
      
      const flatMenus = flattenMenus(tableData.value)
      menuTreeData.value = buildTree(flatMenus)
    }
    
    // 展开全部
    const handleExpandAll = () => {
      defaultExpandAll.value = true
    }
    
    // 收起全部
    const handleCollapseAll = () => {
      defaultExpandAll.value = false
    }
    
    // 刷新
    const handleRefresh = () => {
      fetchMenus()
    }
    
    // 新增
    const handleAdd = () => {
      dialogTitle.value = '新增菜单'
      resetForm()
      dialogVisible.value = true
    }
    
    // 新增子菜单
    const handleAddChild = (row) => {
      dialogTitle.value = '新增子菜单'
      resetForm()
      form.parentId = row.id
      dialogVisible.value = true
    }
    
    // 编辑
    const handleEdit = (row) => {
      dialogTitle.value = '编辑菜单'
      Object.assign(form, {
        id: row.id,
        parentId: row.parentId,
        name: row.name,
        path: row.path,
        component: row.component,
        icon: row.icon,
        sort: row.sort,
        status: row.status,
        description: row.description || ''
      })
      dialogVisible.value = true
    }
    
    // 删除
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除这个菜单吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await api.delete(`/menus/${row.id}`)
        if (response.data.code === 200) {
          ElMessage.success('删除成功')
          fetchMenus()
        }
      } catch (error) {
        if (error !== 'cancel') {
          const errorMessage = error.response?.data?.message || '删除失败'
          ElMessage.error(errorMessage)
        }
      }
    }
    
    // 提交表单
    const handleSubmit = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
      } catch (error) {
        return
      }
      
      submitLoading.value = true
      
      const isEdit = !!form.id
      
      try {
        const url = isEdit ? `/menus/${form.id}` : '/menus'
        const method = isEdit ? 'put' : 'post'
        
        const response = await api[method](url, form)
        if (response.data.code === 200) {
          ElMessage.success(isEdit ? '更新成功' : '创建成功')
          dialogVisible.value = false
          fetchMenus()
        }
      } catch (error) {
        const errorMessage = error.response?.data?.message || (isEdit ? '更新失败' : '创建失败')
        ElMessage.error(errorMessage)
      } finally {
        submitLoading.value = false
      }
    }
    
    // 重置表单
    const resetForm = () => {
      Object.assign(form, {
        id: null,
        parentId: null,
        name: '',
        path: '',
        component: '',
        icon: '',
        sort: 0,
        status: true,
        description: ''
      })
    }
    
    // 关闭对话框
    const handleDialogClose = () => {
      resetForm()
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    }
    
    onMounted(() => {
      fetchMenus()
    })
    
    return {
      loading,
      submitLoading,
      dialogVisible,
      dialogTitle,
      formRef,
      defaultExpandAll,
      tableData,
      menuTreeData,
      form,
      rules,
      fetchMenus,
      handleExpandAll,
      handleCollapseAll,
      handleRefresh,
      handleAdd,
      handleAddChild,
      handleEdit,
      handleDelete,
      handleSubmit,
      handleDialogClose
    }
  }
}
</script>

<style scoped>
.menus-page {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.action-section {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-left {
  display: flex;
  gap: 10px;
}

.table-section {
  margin-bottom: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .action-section {
    flex-direction: column;
    gap: 10px;
  }
  
  .action-left {
    flex-wrap: wrap;
  }
}
</style>
